#!/usr/bin/env python
# encoding=utf-8
"""
@see at : http://120.26.93.104:44444/
"""
import sys

from cassandra.cluster import Cluster
from flask import *
from scpy.logger import get_logger
from xtls.timeparser import now, parse_time

reload(sys)
sys.setdefaultencoding('utf-8')
app = Flask(__name__)

logger = get_logger(__file__)
CASSANDRA_CLUSTER = Cluster(['10.252.101.196', '10.162.88.158', '10.51.35.222'], 9042)
NEWS_SESSION = CASSANDRA_CLUSTER.connect('crawler')
SQL = u'INSERT INTO news_by_company_name (company_name,period,url,content,time) VALUES (?,?,?,?,?)'
INSERT_STMT = NEWS_SESSION.prepare(SQL)

HTML = u'''
<html>
<head><title>新增公司新闻</title></head>
<body style="text-align: center">
<h1>新增公司新闻</h1>

<form action="" method="POST">

公司全称：<input name="companyName" type="text"><br>
新闻标题：<input name="title" type="text"><br>
新闻链接：<input name="url" type="text"><br>
新闻来源：<input name="source" type="text"><br>
新闻时间：<input name="time" type="text"><br>
搜索关键字：<input name="keys" type="text"><br><br>
新闻摘要：<textarea name="abstract" rows="5" cols="40"></textarea><br>
新闻正文：<textarea name="content" rows="10" cols="40"></textarea><br>
<input type="submit">
<hr>
<b>
注意：
<p>新闻链接必须有http或者https前缀！</p>
<p>新闻时间必须为<i><u>2010-01-01 00:00:00</u></i>格式</p>
<p>搜索关键字以英文逗号分隔</p>
</b>

<script>
%s
</script>

</body>
</html>
'''


def save(company, news):
    period = 2016
    stmt = INSERT_STMT.bind([company, period, news['url'], json.dumps(news, ensure_ascii=False), now()])
    NEWS_SESSION.execute(stmt)


@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'GET':
        return HTML
    company_name = request.form.get('companyName').strip()
    title = request.form.get('title').strip()
    url = request.form.get('url').strip()
    source = request.form.get('source').strip()
    time = request.form.get('time').strip()
    keys = request.form.get('keys').strip()
    abstract = request.form.get('abstract').strip()
    content = request.form.get('content').strip()

    if (not company_name) or (not title) or (not url) or (not keys) or (not abstract) or (not content):
        return Response('bad request', 400)
    if not url.startswith('http'):
        return Response('bad request', 400)
    if parse_time(time) != time:
        return Response('bad request', 400)
    news = {
        'title': title,
        'url': url,
        'source': source,
        'time': time,
        'abstract': abstract,
        'content': content,
        'keys': [key.strip() for key in keys.split(',') if key.strip()]
    }
    save(company_name, news)
    return HTML % u'alert("插入成功!")'


if __name__ == '__main__':
    app.run('0.0.0.0', 4444)
